package com.lin.customNamespace.config.beanPostProcessor;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;

import java.lang.reflect.Proxy;
import java.text.SimpleDateFormat;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class TimeLogBeanPostProcessor implements BeanPostProcessor {
    // 创建锁
    private static final Lock lock = new ReentrantLock();
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        lock.lock();
        try {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            return Proxy.newProxyInstance(
                    bean.getClass().getClassLoader(),
                    bean.getClass().getInterfaces(),
                    ((proxy, method, args) -> {
                        System.out.println("method: " + method.getName() +
                                ", 开始执行时间: " + simpleDateFormat.format(System.currentTimeMillis()));
                        Object invoke = method.invoke(bean, args);
                        System.out.println("method: " + method.getName() +
                                ", 结束执行时间: " + simpleDateFormat.format(System.currentTimeMillis()) + "\n");
                        return invoke;
                    })
            );
        } finally {
            lock.unlock();
        }

    }
}
